package com.sz.framework.base;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;

import com.blankj.utilcode.util.LogUtils;
import com.sz.framework.R;
import com.sz.framework.mvp.IBaseView;
import com.sz.framework.utils.ActivityStackManager;
import com.sz.framework.utils.ToastUtil;
import com.sz.framework.widget.LoadingDialog;

import butterknife.ButterKnife;
import butterknife.Unbinder;

public abstract class BaseActivity extends AppCompatActivity implements IBaseView {
    private LoadingDialog loadingDialog;
    private Unbinder mUnBinder;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        LogUtils.e("< == page == >" + this.getClass().getSimpleName());
        ActivityStackManager.getInstance().pushActivity(this);
        setContentView(generateLayout());
        mUnBinder = ButterKnife.bind(this);
        initTitleBar();
    }

    @Override
    public void initTitleBar() {

    }

    @Override
    public void showToastMessage(String msg) {
        ToastUtil.showToast(msg);
    }

    @Override
    public void showToastMessage(int resId) {
        ToastUtil.showToast(resId);
    }


    @Override
    public void showLoadingDialog(String msg) {
        if (isFinishing()) {
            return;
        }
        getDialog(this, msg).show();
    }

    @Override
    public void showLoadingDialog() {
        showLoadingDialog(null);
    }

    private LoadingDialog getDialog(Context context, String content) {
        if (null == loadingDialog) {
            loadingDialog = new LoadingDialog(context);
        }
        if (!TextUtils.isEmpty(content)) {
            loadingDialog.setMessage(content);
        } else {
            loadingDialog.setMessage(getString(R.string.refresh_text));
        }
        return loadingDialog;
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mUnBinder != null && mUnBinder != Unbinder.EMPTY){
            try {
                mUnBinder.unbind();
                mUnBinder = null;
            } catch (IllegalStateException e) {
                e.printStackTrace();
                LogUtils.w("onDestroy: " + e.getMessage());
            }
        }
        ActivityStackManager.getInstance().popActivity(this);
        if (null != loadingDialog) {
            loadingDialog.cancel();
            loadingDialog = null;
        }
    }

    @Override
    public void goLogin() {

    }

    @Override
    public Context getContext() {
        return this;
    }

    @Override
    public void onError(String msg) {
        showToastMessage(msg);
    }

    @Override
    public void cancelLoadingDialog() {
        if (null != loadingDialog){
            loadingDialog.cancel();
        }
    }
}
